using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;

namespace Lzfy_Refund_Service.Services
{
    /// <summary>
    /// 线上退费记录服务实现
    /// </summary>
    public class PrepayRefundDetailService : IPrepayRefundDetailService
    {
        private readonly IPrepayRefundDetailRepository _prepayRefundDetailRepository;
        private readonly ILogger<PrepayRefundDetailService> _logger;

        public PrepayRefundDetailService(
            IPrepayRefundDetailRepository prepayRefundDetailRepository,
            ILogger<PrepayRefundDetailService> logger)
        {
            _prepayRefundDetailRepository = prepayRefundDetailRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取线上退费记录列表（分页）
        /// </summary>
        public async Task<(List<PrepayRefundDetail> records, int totalCount)> GetPrepayRefundDetailListAsync(
            string? patientId = null,
            string? patName = null,
            string? balanceSn = null,
            DateTime? startDate = null,
            DateTime? endDate = null,
            int pageIndex = 1,
            int pageSize = 20)
        {
            return await _prepayRefundDetailRepository.GetPrepayRefundDetailListAsync(
                patientId, patName, balanceSn, startDate, endDate, pageIndex, pageSize);
        }

        /// <summary>
        /// 根据退费流水号获取线上退费记录
        /// </summary>
        public async Task<PrepayRefundDetail?> GetPrepayRefundDetailByBalanceSnAsync(string balanceSn)
        {
            return await _prepayRefundDetailRepository.GetPrepayRefundDetailByBalanceSnAsync(balanceSn);
        }

        /// <summary>
        /// 根据患者ID获取线上退费记录列表
        /// </summary>
        public async Task<List<PrepayRefundDetail>> GetPrepayRefundDetailsByPatientIdAsync(string patientId)
        {
            return await _prepayRefundDetailRepository.GetPrepayRefundDetailsByPatientIdAsync(patientId);
        }

        /// <summary>
        /// 创建线上退费记录
        /// </summary>
        public async Task<bool> CreatePrepayRefundDetailAsync(PrepayRefundDetailCreateRequest request)
        {
            // 检查退费流水号是否已存在
            if (await _prepayRefundDetailRepository.IsBalanceSnExistsAsync(request.BalanceSn))
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 已存在", request.BalanceSn);
                return false;
            }

            var prepayRefundDetail = new PrepayRefundDetail
            {
                BalanceSn = request.BalanceSn,
                InputDate = DateTime.Now,
                RefundBalance = request.RefundBalance,
                PatientId = request.PatientId,
                PatName = request.PatName,
                RefundTypeName = request.RefundTypeName,
                AuditDate = request.AuditDate,
                AcctDate = request.AcctDate,
                AuditUserId = request.AuditUserId,
                AuditUserName = request.AuditUserName,
                BankCardHolder = request.BankCardHolder,
                AcctId = request.AcctId,
                RefundBankCity = request.RefundBankCity,
                PublicAgentRefundBankCity = request.PublicAgentRefundBankCity
            };

            return await _prepayRefundDetailRepository.CreatePrepayRefundDetailAsync(prepayRefundDetail);
        }

        /// <summary>
        /// 更新线上退费记录
        /// </summary>
        public async Task<bool> UpdatePrepayRefundDetailAsync(PrepayRefundDetailUpdateRequest request)
        {
            // 检查退费记录是否存在
            var existingRecord = await _prepayRefundDetailRepository.GetPrepayRefundDetailByBalanceSnAsync(request.BalanceSn);
            if (existingRecord == null)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 不存在", request.BalanceSn);
                return false;
            }

            // 检查是否已审核，已审核的记录不允许修改
            if (existingRecord.AuditDate.HasValue)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 已审核，不允许修改", request.BalanceSn);
                return false;
            }

            // 更新记录
            existingRecord.RefundBalance = request.RefundBalance;
            existingRecord.RefundTypeName = request.RefundTypeName;
            existingRecord.BankCardHolder = request.BankCardHolder;
            existingRecord.AcctId = request.AcctId;
            existingRecord.RefundBankCity = request.RefundBankCity;
            existingRecord.PublicAgentRefundBankCity = request.PublicAgentRefundBankCity;

            return await _prepayRefundDetailRepository.UpdatePrepayRefundDetailAsync(existingRecord);
        }

        /// <summary>
        /// 删除线上退费记录
        /// </summary>
        public async Task<bool> DeletePrepayRefundDetailAsync(string balanceSn)
        {
            // 检查退费记录是否存在
            var existingRecord = await _prepayRefundDetailRepository.GetPrepayRefundDetailByBalanceSnAsync(balanceSn);
            if (existingRecord == null)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 不存在", balanceSn);
                return false;
            }

            // 检查是否已审核，已审核的记录不允许删除
            if (existingRecord.AuditDate.HasValue)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 已审核，不允许删除", balanceSn);
                return false;
            }

            return await _prepayRefundDetailRepository.DeletePrepayRefundDetailAsync(balanceSn);
        }

        /// <summary>
        /// 审核线上退费记录
        /// </summary>
        public async Task<bool> AuditPrepayRefundDetailAsync(PrepayRefundDetailAuditRequest request)
        {
            // 检查退费记录是否存在
            var existingRecord = await _prepayRefundDetailRepository.GetPrepayRefundDetailByBalanceSnAsync(request.BalanceSn);
            if (existingRecord == null)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 不存在", request.BalanceSn);
                return false;
            }

            // 检查是否已审核
            if (existingRecord.AuditDate.HasValue)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 已审核，不允许重复审核", request.BalanceSn);
                return false;
            }

            return await _prepayRefundDetailRepository.AuditPrepayRefundDetailAsync(
                request.BalanceSn, request.AuditUserId, request.AuditUserName);
        }

        /// <summary>
        /// 结算线上退费记录
        /// </summary>
        public async Task<bool> SettlePrepayRefundDetailAsync(string balanceSn)
        {
            // 检查退费记录是否存在
            var existingRecord = await _prepayRefundDetailRepository.GetPrepayRefundDetailByBalanceSnAsync(balanceSn);
            if (existingRecord == null)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 不存在", balanceSn);
                return false;
            }

            // 检查是否已审核，未审核的记录不允许结算
            if (!existingRecord.AuditDate.HasValue)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 未审核，不允许结算", balanceSn);
                return false;
            }

            // 检查是否已结算
            if (existingRecord.AcctDate.HasValue)
            {
                _logger.LogWarning("退费流水号 {BalanceSn} 已结算，不允许重复结算", balanceSn);
                return false;
            }

            return await _prepayRefundDetailRepository.SettlePrepayRefundDetailAsync(balanceSn);
        }
    }
}